<?php
// +----------------------------------------------------------------------
// | 墓区管理
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\CemeteryModel;
use app\admin\model\TombareaModel;
use app\admin\model\TombareaRowModel;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\AdminMenuModel;
use think\helper\Arr;
use tree\Tree;
use think\facade\Request;

class TombareaController extends AdminBaseController
{

    //获取导航列表及子列表
    protected $temp;
    public function initialize()
    {
        $this->deal_model = Db::name("tombarea");
        $this->row_model = Db::name("tombareaRow");
        $this->col_model = Db::name("tombareaRowCol");
		$this->cemetery_model = new CemeteryModel();
        parent::initialize();
    }
	public function index(){
        $parentid = $this->request->param('parentid', 0, 'intval');
        $id = $this->request->param('id', 0, 'intval');
        $this->assign("id",$id);
        $this->assign("parentid",$parentid);
        //查询墓区信息
        $result = $this->deal_model->alias("d")->where(array("cemetery_id"=>$id))->order('list_order asc ')->select();

        $result_list=[];
        foreach ($result as $key=>&$val){
            $first_name = $this->cemetery_model->getNavCates($val['cemetery_id']);
            $val['first_name'] = $first_name;
            $val['cate_name'] = $this->cate_arr[$val['cate_id']];
            $result_list[]= $val;
        }
        $this->assign("results",$result_list);
        return $this->fetch();
	}
	public function add(){
        if ($this->request->isPost()){
            $model = new TombareaModel();
            $data = $this->request->param();
            $res = $model->doDataSave($data);
            if ($res!==false){
                return $this->success("添加成功", url('index',['parentid'=>$data['tm']['parentid'],'id'=>$data['tm']['cemetery_id']]));
            }else{
                return $this->error($model->getError());
            }
        }
		$tree = new Tree();
        $parentid = $this->request->param('parentid', 0, 'intval');
		$id = $this->request->param('id', 0, 'intval');
    	$result = $this->cemetery_model->order(array("list_order" => "ASC"))->select()->toArray();
    	foreach ($result as $r) {
    		$r['selected'] = $r['id'] == $id ? 'selected' : '';
    		$array[] = $r;
    	}
    	$str = "<option value='\$id' \$selected>\$spacer \$name</option>";
    	$tree->init($array);
    	$select_categorys = $tree->getTree(0, $str);
    	$this->assign("select_categorys", $select_categorys);
    	$this->assign("id",$id);
        $this->assign("parentid",$parentid);
		return $this->fetch();
	}
	// 墓产品信息
	public function product(){
//        $tomb_id = $this->request->param();
//        exit(json_encode($tomb_id));
        $tombar_id = $this->request->param('tomb_id',0,'intval');
//        $tombar_id = $this->request->param('tombar_id', 0, 'intval');
        $this->assign("tombar_id",$tombar_id);

        $data = Db::name("tombarea_product")->where(array("tombar_id"=>$tombar_id))->find();
        if(empty($data["id"])){
            $this->assign("id",0);
            $data = array(
                "pro_status"    => 1,
                "footprint"     => '',
                "tombstone_h"   => '',
                "tomb_regulation"=> 1,
                "warranty"      => 1,
                "specifications"=> '',
                "green_belt"    => '',
                "selling_price" => '',
                "manage_cycle"  => 1,
                "supplier"      => '',
                "old_pro"       => '',
                "new_pro"       => ''
            );

        }else{
            $this->assign("id",$data["id"]);
        }
        $this->assign($data);

        $result = Db::name("product")->field("id,pro_name as name,pro_address  ")->select();

        $this->assign("product",$result);

        // 石材种类
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")-> join("dj_cate c","c.id = s.cate_id","left") ->select();
        $this->assign("cate_type",json_encode($cate_type));

        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annexJson", json_encode($annex));

        // 陵园id
        $cemeData = Db::name("tombarea")->alias('s')->field("c.id,c.parent_id")-> join("dj_cemetery c","c.id = s.cemetery_id","left")->where(array('s.id'=>$tombar_id)) ->find();
        $this->assign("ceme_id", $cemeData['id']);
        $this->assign("parent_id", $cemeData['parent_id']);
		return $this->fetch();
	}
	// 墓碑产品详情
    public function getProductInfo(){
        $id = $this->request->param("id");
        $data = Db::name("product")->alias('s')->field("s.*,p.pro_name as name")-> join("dj_product p","p.id = s.change_id","left")->where(array("s.id"=>$id)) ->find();
        // 详情
        $infowhere = array(
            'pro_id' => $id,
            'itype' => 1
        );
        $infoData = Db::name("product_info")->where($infowhere)->select();
        // 基础
        $basewhere = array(
            'pro_id' => $id,
            'itype' => 2
        );
        $baseData = Db::name("product_info")->where($basewhere)->select();
        // 盖板
        $platewhere = array(
            'pro_id' => $id,
            'itype' => 3
        );
        $plateData = Db::name("product_info")->where($platewhere)->select();
        // 栏杆
        $railwhere = array(
            'pro_id' => $id,
            'itype' => 4
        );
        $railData = Db::name("product_info")->where($railwhere)->select();
        // 附件
        $annexwhere = array(
            'pro_id' => $id,
        );
        $annexData = Db::name("product_annex")->where($annexwhere)->select();


        $result = array(
            'infoData' => $infoData,
            'baseData' => $baseData,
            'plateData' => $plateData,
            'railData' => $railData,
            'annexData' => $annexData,
            'data'=>$data
        );

        exit(json_encode($result));
    }

    public function productadd_post(){
        // 墓区id
        $tombar_id = $this->request->param('tombar_id');
        $data = $this->request->param();
        if($data['id'] != 0){
            Db::name("tombarea_product")->where('id', $data['id']) ->delete();
        }

        $productData['tombar_id'] = $tombar_id;
        $productData['pro_status'] = $data['pro_status'];
        $productData['footprint'] = $data['footprint'];
        $productData['tombstone_h'] = $data['tombstone_h'];
        $productData['tomb_regulation'] = $data['tomb_regulation'];
        $productData['warranty'] = $data['warranty'];
        $productData['specifications'] = $data['specifications'];
        $productData['green_belt'] = $data['green_belt'];
        $productData['selling_price'] = $data['selling_price'];
        $productData['manage_cycle'] = $data['manage_cycle'];
        $productData['supplier'] = $data['supplier'];
        $productData['old_pro'] = $data['old_pro'];
        $productData['new_pro'] = $data['new_pro'];
//        $productData['pro_photo'] = $data['pro_photo'];
        $productData['add_user'] = cmf_get_current_admin_id();
        $productData['add_time'] = time();


        $ret = Db::name("tombarea_product")->insert($productData);
        if ($ret){
            Db::name("tombarea_row_col")->where(['tombarea_id'=>$tombar_id])->update(['col_status'=>1]);
        }
        // 陵园id
        $cemeData = Db::name("tombarea")->alias('s')->field("c.id,c.parent_id")-> join("dj_cemetery c","c.id = s.cemetery_id","left")->where(array('s.id'=>$tombar_id)) ->find();
        $id = $cemeData['id'];
        $parent_id = $cemeData['parent_id'];

        $this->success("保存成功",url("tombarea/index",array('parentid'=>$parent_id,'id'=>$id)));
    }
    public function productinfo(){

        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")-> join("dj_cate c","c.id = s.cate_id","left") ->select();
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));

        return $this->fetch();
    }

    public function productinfo_post(){
        if ($this->request->isPost()){
            $param = $this->request->param();

        }

    }

    public function sele(){
        $this->assign('ll',45454546);
        return $this->fetch();
    }

    /**
     *   停用
     * 添加数据
     */
    public function add_post()
    {

//        添加主表数据
        $data = $this->request->param();
        if (!isset($data['name'])|| empty($data['name'])){
            $this->error("请填写名称");
        }  if (!isset($data['paihao'])|| empty($data['paihao'])){
            $this->error("请选择墓位排号");
        }

        $types = $data['types'];
        unset($data['types']);
        for($i=0;$i<count($data['paihao']);$i++){
            if(empty($data['paihao'][$i])){
                $this->error("请生成墓位排号");
            }
            if(empty($data['wei'][$i])){
                $this->error("请确认墓位人数");
            }
        }
        if (!isset($data['num'])&& empty($data['num'])){
            $this->error("请生成排号，并写入墓位编号");
        }
        $data['add_user'] = cmf_get_current_admin_id();
        $data['add_time'] = time();

        Db::startTrans();
        try {
            unset($data['paihao']);unset($data['wei']);unset($data['num']);unset($data['reacher']);unset($data['statusinfo']);
            unset($data['parentid']);unset($data['id']);
            $tombid = $this->deal_model->insertGetId($data);
            //根据生成id去新增墓位数据
            $info = $this->request->param();
            $tomb['tombarea_id'] = $tombid;
            $paihao = $info['paihao'];
            $wei = $info['wei'];
            //c此处报错，需多次插入
            $colid = array();
            for($i = 0; $i < count($paihao); $i++){
                $tomb['num'] = $paihao[$i];
                $tomb['column'] = $wei[$i];
                $colid[] = Db::name("tombareaRow")->insertGetId($tomb);
            }
            $tom_id = $this->addTombcol($colid,$data['cate_id'],$tombid);
            //修改陵园是否生成墓区
            $cemeteryData['is_generate'] = 1;
            Db::name("cemetery")->where('id', $data['cemetery_id'])->update($cemeteryData);

            Db::commit();
        }catch(\Exception $e){
            $this->error('墓位编号重复');
            Db::rollback();
        }
//        exit(json_encode([$tom_id,$colid,$tombid]));
        if ($types==1){

            $this->success("保存成功",url(Request::controller()."/product",array('tomb_id'=>$tombid,'tom_id'=>$tom_id)));
        }else{
            $this->success("添加成功", url(Request::controller().'/index',array('parentid'=>$info['parentid'],'id'=>$info['id'])));
        }

    }
    /**
     *  停用
     * 添加墓位信息
     * @param $colid
     */
    public function addTombcol($colid,$cate_id,$tombarea_id){
        $info = $this->request->param();
        //行数
        $hang = $info['row'];
        $wei = $info['wei'];
        $col = array();
        $mId='';
        $ij_num = 0;
        for ($i=0;$i<$hang;$i++){
            for ($j=0;$j<$wei[$i];$j++){
                //判断编号是否存在，如果存在，则退出
                $col = Db::name("tombareaRowCol")->where("num",$info['num'][$ij_num])->find();
                if(!empty($col)){
                    $this->error($info['num'][$j+$j*$i].'墓位编号重复');
                    Db::rollback();
                }else {
                    $col = [
                        'rowid' => $colid[$i],
                        'num' => $info['num'][$ij_num],
                        'reacher' => "",
                        'cate_id' => $cate_id,
                        'tombarea_id' => $tombarea_id,
                        'status' => $info['statusinfo'][$ij_num],
                        'rows_num' => $i + 1,
                        'column_num' => $j + 1,
                        'col_status' => $cate_id == 3 ? 0 : ($cate_id == 4 ? 0 : 4)
                    ];
                    $colId = Db::name("tombareaRowCol")->insertGetId($col);
                    $mId = !empty($mId) ? $mId . ',' . $colId : $colId;
                    $ij_num++;
                }
            }
        }

        return $mId;
    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     * @return true
     */
    protected function _get_level($id, $array = array(), $i = 0) {
        
        	if ($array[$id]['parent_id']==0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id']==$id){
        		return  $i;
        	}else{
        		$i++;
        		return $this->_get_level($array[$id]['parent_id'],$array,$i);
        	}
        		
    }
    /**
     * 下拉数据
     */
    public function getALlOption(){
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")-> join("dj_cate c","c.id = s.cate_id","left") ->select();
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));
        exit(json_encode($cate_type));
        // 所有产品库
        $allData = Db::name("product")->field("id,pro_name as name")->select();
        $this->assign("allData", $allData);
        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annex", $annex);
        $this->assign("annexJson", json_encode($annex));
    }
    /**
     * 删除墓区数据
     **/
    public function delete(){
        // 需要删除的数据ID
        $id = $this->request->param("id",0,'intval');

        // 删除之前判断该墓区下墓位有没有无规划和无产品以外的状态则不允许删除
        $listre = $this->col_model->field("colID")->where("tombarea_id",$id)->where("col_status","<>",4)->where("col_status","<>",0)->select();

        if(count($listre) != 0){
            return $this->error("该墓区下的墓位有除无规划和无产品以外的状态，不允许删除！");
        }
        $TombareaModel = new TombareaModel();
        $res =  $TombareaModel->tomDelete($id);
        if($res){
            return $this->success("删除成功");
        }else{
            return $this->error($TombareaModel->getError());
        }
    }
}
